<?php
namespace app\admin\controller;

use app\model\usersModel;
use think\facade\Request;
use think\facade\Validate;
use think\facade\View;

class users{
    public function index()
    {
        $usersList = usersModel::select();
        View::assign('usersList',$usersList);
        return View::fetch("users/index");
    }

    public function edit()
    {
        $user_id = Request::param('user_id');
        $validate = Validate::rule([
            'user_id|用户id' => 'request|between:1,'.PHP_INT_MAX,
        ]);

        if(!$validate->check(['user_id'=>$user_id])){
            echo $validate->getError();
            exit();
        }
        $userList = usersModel::where('user_id','=',$user_id)->find();

        View::assign('userList',$userList);
        return View::fetch();
    }

    public function editSave()
    {
        $params = Request::param();
        $validate = Validate::rule([
            'user_id|用户id' => 'request|between:1,'.PHP_INT_MAX,
            'user_name|用户名' => 'request',
            'user_email|邮箱' => 'request',
            'user_pwd|密码' => 'request',
            'pwds|确认密码' => 'request',
        ]);

        if(!$validate->check($params)){
            echo $validate->getError();
            exit();
        }
        if($params['user_pwd'] != $params['pwds']){
            echo '两次密码不一致,请重新输入';
            echo '<a href="javascript:void(0)" onclick="history.back();">返回上一页</a>';
            exit();
        }
        $params["update_time"] = time();

        $result = usersModel::update($params);

        if ($result) {
            echo "<script>alert('编辑成功');</script>";
            echo "<script>location.href='/index.php?s=admin/users/index'</script>";
        } else {
            echo "<script>alert('编辑失败,请联系管理员：1292888678@qq.com');</script>";
        }
    }

    public function delete()
    {
        $user_id = Request::param('user_id');
        $validate = Validate::rule([
            'user_id|用户id' => 'require|between:1,'.PHP_INT_MAX,
        ]);

        if(!$validate->check(['user_id'=>$user_id])){
            echo $validate->getError();
            exit();
        }
        $result = usersModel::destroy($user_id);

        if ($result) {
            echo "<script>alert('删除成功');</script>";
            echo "<script>location.href='/index.php?s=admin/users/index'</script>";
        } else {
            echo "<script>alert('删除失败,请联系管理员：1292888678@qq.com');</script>";
        }
    }
}